package com.baizhi.fitler;

import com.baizhi.constants.RedisPrefix;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.server.RequestPath;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

//自定义网关filter
//@Configuration
public class TokenGlobalFitler implements GlobalFilter, Ordered {

    private final RedisTemplate redisTemplate;

    @Autowired
    public TokenGlobalFitler(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private static final Logger log = LoggerFactory.getLogger(TokenGlobalFitler.class);

    /**
     * 不需要token的
     * tokens 登录
     * captchas 验证码
     * categories分类
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.当请求路径为tokens时不需要强制认证
        RequestPath path = exchange.getRequest().getPath();
        log.info("path: {}", path);
        //2.排除登录路径
        if (!StringUtils.equals(path.toString(), "/tokens")) {
            if (!StringUtils.equals(path.toString(), "/captchas")) {
                //路径中包含captchas全部放行
                if (!path.toString().contains("/categories") && !path.toString().contains("/recommends")
                        && !path.toString().contains("/videos/videos") && !path.toString().contains("/videos/user/played")) {
                    //3.根据传递token验证token在redis中是否存在 ?name=xiaochen&name=
                    List<String> tokens = exchange.getRequest().getQueryParams().get("token");
                    if (tokens == null) throw new RuntimeException("提示: 不合法令牌!");
                    String token = tokens.get(0);
                    String key = RedisPrefix.USER_TOKEN_PREFIX + token;
                    ValueOperations valueOperations = redisTemplate.opsForValue();
                    Object o = valueOperations.get(key);
                    //4.根据token信息 去redis中验证
                    if (!redisTemplate.hasKey(RedisPrefix.USER_TOKEN_PREFIX + token)) {
                        throw new RuntimeException("提示: 无效令牌!");
                    }
                }
            }
        }
        return chain.filter(exchange);
    }

    //-1 在所有filter之前执行
    @Override
    public int getOrder() {
        return -1;
    }
}
